package cn.arikeky.service.impl;

import cn.arikeky.domain.MoveUser;
import cn.arikeky.domain.MovieTicket;
import cn.arikeky.domain.User;
import cn.arikeky.dto.BuyDto;
import cn.arikeky.exception.GlobalExceptionEnum;
import cn.arikeky.mapper.MoveUserMapper;
import cn.arikeky.mapper.MovieTicketMapper;
import cn.arikeky.result.JsonResult;
import cn.arikeky.service.IMoveUserService;
import cn.arikeky.service.IMovieTicketService;
import cn.arikeky.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author director
 * @since 2022-11-23
 */
@Service
public class MovieTicketServiceImpl extends ServiceImpl<MovieTicketMapper, MovieTicket> implements IMovieTicketService {

    @Autowired
    private MovieTicketMapper movieTicketMapper;

    @Autowired
    private IMoveUserService moveUserService;


    @Override
    public JsonResult buy(Long movieId, Integer count) {
        selectMovie(movieId, count);

        EntityWrapper<MoveUser> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id",1L);
        wrapper.eq("movie_ticket_id", movieId);
        MoveUser selectOne = moveUserService.selectOne(wrapper);
        if (selectOne == null){
            MoveUser moveUser = new MoveUser();
            moveUser.setUserId(1L);
            moveUser.setCount(count);
            moveUser.setMovieTicketId(movieId);
            moveUserService.insert(moveUser);
        } else {
            selectOne.setCount(selectOne.getCount() + count);
            moveUserService.updateById(selectOne);
        }

        return JsonResult.success();
    }

    private void selectMovie(Long movieId, Integer count) {
        MovieTicket movieTicket = selectById(movieId);
        AssertUtil.isNotNull(movieTicket, GlobalExceptionEnum.ERROR);
        movieTicket.setStock(movieTicket.getStock() - count);
        updateById(movieTicket);
    }



    @Override
    public JsonResult give(Long movieId, Integer count, Long userId) {
        selectMovie(movieId, count);

        MoveUser moveUser = new MoveUser();
        moveUser.setUserId(1L);
        moveUser.setCount(count);
        moveUser.setMovieTicketId(movieId);
        moveUserService.insert(moveUser);
        return JsonResult.success("赠送成功！");
    }


}
